<template>
  <!-- 折线图6  -->
  <div ref="index" class="index"></div>
</template>
<script setup lang="ts">
import * as echarts from "echarts";
import { ref, watch, nextTick } from "vue";
// 接收值
let props = defineProps({
  carData: {
    type: Object,
    default: false,
  },
});
// 定义值
let index = ref(); //ref的应用
// 定义加载函数
let initCharts = () => {
  let chart = echarts.init(index.value);
  // 转为系统时间显示
  const format = (_date, _format) => {
    if (!_date) return "";
    if (!_date.getDate) _date = new Date(_date);
    _format = _format || "yyyy-MM-dd hh:mm:ss";
    const o = {
      "y+": _date.getFullYear(),
      "M+": _date.getMonth() + 1, // 月份
      "d+": _date.getDate(), // 日
      "h+": _date.getHours(), // 小时
      "m+": _date.getMinutes(), // 分
      "s+": _date.getSeconds(), // 秒
      "q+": Math.floor((_date.getMonth() + 3) / 3), // 季度
      S: _date.getMilliseconds(), // 毫秒
    };
    if (/(y+)/.test(_format)) {
      _format = _format.replace(
        RegExp.$1,
        `${_date.getFullYear()}`.substr(4 - RegExp.$1.length)
      );
    }
    for (const k in o) {
      if (new RegExp(`(${k})`).test(_format)) {
        _format = _format.replace(
          RegExp.$1,
          RegExp.$1.length == 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
        );
      }
    }

    return _format;
  };

  // 生成24个随机整数
  function generateRandomNumbers() {
    const randomNumbers = [];
    for (let i = 0; i < 24; i++) {
      randomNumbers.push(Math.floor(Math.random() * 100));
    }
    return randomNumbers;
  }
  let xData = [
    "11-17 16:00",
    "11-17 17:00",
    "11-17 18:00",
    "11-17 19:00",
    "11-17 20:00",
    "11-17 21:00",
    "11-17 22:00",
    "11-17 23:00",
    "11-18 00:00",
    "11-18 01:00",
    "11-18 02:00",
    "11-18 03:00",
    "11-18 04:00",
    "11-18 05:00",
    "11-18 06:00",
    "11-18 07:00",
    "11-18 08:00",
    "11-18 09:00",
    "11-18 10:00",
    "11-18 11:00",
    "11-18 12:00",
    "11-18 13:00",
    "11-18 14:00",
    "11-18 15:00",
    "11-18 16:00",
  ];
  const yData = [
    {
      name: "消息",
      data: [
        341, 441, 541, 641, 741, 841, 941, 131, 231, 331, 431, 531, 631, 731,
        831, 931, 151, 251, 351, 451, 551, 651, 751,
      ],
    },
    {
      name: "指令",
      data: [
        232, 332, 432, 532, 632, 732, 832, 932, 142, 242, 342, 442, 542, 642,
        742, 842, 942, 162, 262, 362, 462, 562,
      ],
    },
    {
      name: "信息",
      data: [
        153, 253, 353, 453, 553, 653, 753, 400, 600, 200, 400, 200, 253, 400,
        560, 145, 800, 542, 200, 700, 400, 789, 100, 465,
      ],
    },
  ];

  const colorList = ["#298CFF", "#533DF1", "#44E2FE"];

  const tooltip = {
    trigger: "axis",
    axisPointer: {
      type: "line",
    },
    textStyle: {
      color: "#fafafa",
    },
    borderColor: "transparent",
    backgroundColor: "rgba(0, 0, 0, 0.5)",
    extraCssText: "backdrop-filter: blur(6px);",
  };
  const grid = {
    top: "20%",
    left: "2%",
    right: "8%",
    bottom: "0%",
    containLabel: true,
  };
  const legend = {
    show: true,
    right: 20,
    icon: "roundRect",
    itemHeight: 5,
    itemWidth: 10,
    // itemGap: 40,
    textStyle: {
      color: "#d0d0d0",
      align: "center",
      fontSize: 10,
    },
  };

  // 线性渐变
  const seriesCommonFn = (name, data, color) => {
    return {
      name: name,
      data: data,
      type: "line",
      smooth: true,
      showSymbol: false,
      // symbol: 'none',
      symbolSize: 10,
      emphasis: { focus: "series" },
      animationDuration: 2500,
      animationEasing: "cubicInOut",
      lineStyle: {
        width: 6,
        color: {
          type: "linear",
          x: 0,
          y: 0,
          x2: 1,
          y2: 0,
          colorStops: [
            // linear-gradient(89.21deg, rgba(83, 61, 241, 0) -0.8%, #533DF1 51.74%, rgba(83, 61, 241, 0) 99.08%);
            {
              offset: 0 / 100,
              color: "rgba(83, 61, 241, 0)",
            },
            {
              offset: 50 / 100,
              color: color,
            },
            {
              offset: 100 / 100,
              color: "rgba(83, 61, 241, 0)",
            },
          ],
          global: false, // 缺省为 false
        },
      },
    };
  };

  const xAxisFn = (xData) => {
    return [
      {
        type: "category",
        boundaryGap: false,
        data: xData,
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: {
          show: true,
          textStyle: {
            color: "#7ec7ff",
          },
          formatter: (name) => {
            return format(new Date(name), "hh:mm");
          },
        },
        axisPointer: {
          show: true,
          label: {
            formatter: (obj) => {
              let name = obj.value;
              // let start = format(subHours(new Date(name), 1), 'hh:mm')
              let start = format(new Date(name), "hh:mm");
              const arr = [
                Number(start.split(":")[0]) - 1,
                start.split(":")[1],
              ];
              start = arr.join(":");
              let end = format(new Date(name), "hh:mm");
              return `${start}~${end}`;
            },
          },
        },
      },
    ];
  };
  // x--时间坐标轴 线性渐变
  const linearGradient = {
    seriesCommonFn,
    xAxisFn,
  };
  let option = {
    backgroundColor: "rgb(19, 47, 74)",
    series: yData.map((item, index) => {
      return linearGradient.seriesCommonFn(
        item.name,
        item.data,
        colorList[index]
      );
    }),
    tooltip,
    legend: {
      ...legend,
      top: "6%",
      formatter: (name) => {
        let record = yData.find((v) => v.name === name);
        let total = record.data.reduce((x, y) => x + y);
        return `${name}(${total})`;
      },
    },
    grid: {
      ...grid,
      top: "25%",
      // top: 60,
    },
    xAxis: linearGradient.xAxisFn(xData),
    yAxis: [
      {
        type: "value",
        axisLabel: {
          textStyle: {
            color: "#7ec7ff",
          },
        },
      },
    ],
  };
  console.log("[option]", option);

  chart.setOption(option, true);
  // 当窗口大小改变时候，echarts重置大小
  window.addEventListener("resize", () => {
    chart.resize();
  });
};

// 监听当配置项发生变化的时候，调用加载函数
watch(
  () => props.carData,
  (val) => {
    if (Object.keys(val)) {
      nextTick(() => {
        initCharts();
      });
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="less">
.index {
  width: 100%;
  height: 200px;
}
</style>
